package com.inkyi.assistant.app.todolist.table;


import com.inkyi.assistant.app.todolist.TodoContext;
import com.inkyi.assistant.app.todolist.event.TodoEvent;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableModel;

public class TodoListSelectionListener implements ListSelectionListener {


    private final JTable table;
    private final TableModel tableModel;

    public TodoListSelectionListener(JTable table) {
        this.table = table;
        this.tableModel = table.getModel();

    }

    @Override
    public void valueChanged(ListSelectionEvent e) {
        if (e.getValueIsAdjusting()) {
            return;
        }
        int[] selectedRows = table.getSelectedRows();
        if (selectedRows.length == 0) {
            return;
        }
        int selectedRow = selectedRows[0];
        if (tableModel instanceof TodoTableModel) {
            TodoTableModel todoTableModel = (TodoTableModel) tableModel;
            TodoItem todoItem = todoTableModel.getValueByRow(selectedRow);
            if (todoItem != null) {
                TodoContext.getEventWrap().fireActionEvent(TodoEvent.of(e.getSource(), TodoEvent.TYPE_RECORD_SHOW, todoItem));
            }
        }
    }
}
